// utils/storage.js

// 存储键名常量
const STORAGE_KEYS = {
  // 用户相关
  TOKEN: 'token',
  REFRESH_TOKEN: 'refreshToken',
  TOKEN_EXPIRES_IN: 'tokenExpiresIn',
  USER_INFO: 'userInfo',
  USER_SETTINGS: 'userSettings',
  
  // 应用相关
  APP_CONFIG: 'appConfig',
  THEME: 'theme',
  LANGUAGE: 'language',
  
  // 搜索相关
  SEARCH_HISTORY: 'searchHistory',
  RECENT_CAPSULES: 'recentCapsules',
  
  // 缓存相关
  CAPSULE_CACHE: 'capsuleCache',
  ENTRY_CACHE: 'entryCache',
  TEMPLATE_CACHE: 'templateCache',
  
  // 草稿相关
  DRAFT_CAPSULE: 'draftCapsule',
  DRAFT_ENTRY: 'draftEntry',
  
  // 其他
  FIRST_LAUNCH: 'firstLaunch',
  LAST_VERSION: 'lastVersion',
  PRIVACY_AGREED: 'privacyAgreed'
}

/**
 * 存储值类型
 * @typedef {string|number|boolean|object|null} StorageValue
 */

/**
 * 缓存项接口
 * @typedef {Object} CacheItem
 * @property {*} data
 * @property {number} timestamp
 * @property {number} [expireTime]
 */

/**
 * 存储配置接口
 * @typedef {Object} StorageConfig
 * @property {string} [prefix]
 * @property {boolean} [encrypt]
 * @property {boolean} [compress]
 */

// 存储管理器类
class StorageManager {
  constructor(config = {}) {
    this.config = {
      prefix: 'lagain_',
      encrypt: false,
      compress: false,
      ...config
    }
    this.prefix = this.config.prefix || ''
  }

  static getInstance(config) {
    if (!StorageManager.instance) {
      StorageManager.instance = new StorageManager(config)
    }
    return StorageManager.instance
  }

  // 生成完整的存储键名
  getFullKey(key) {
    return `${this.prefix}${key}`
  }

  // 序列化数据
  serialize(value) {
    try {
      const serialized = JSON.stringify(value)
      
      // 如果启用压缩，可以在这里添加压缩逻辑
      if (this.config.compress) {
        // 简单的压缩示例（实际项目中可以使用更好的压缩算法）
        return this.compress(serialized)
      }
      
      // 如果启用加密，可以在这里添加加密逻辑
      if (this.config.encrypt) {
        return this.encrypt(serialized)
      }
      
      return serialized
    } catch (error) {
      console.error('序列化数据失败:', error)
      throw new Error('序列化数据失败')
    }
  }

  // 反序列化数据
  deserialize(value) {
    try {
      let processed = value
      
      // 如果启用加密，先解密
      if (this.config.encrypt) {
        processed = this.decrypt(processed)
      }
      
      // 如果启用压缩，先解压
      if (this.config.compress) {
        processed = this.decompress(processed)
      }
      
      return JSON.parse(processed)
    } catch (error) {
      console.error('反序列化数据失败:', error)
      return null
    }
  }

  // 简单的压缩方法（示例）
  compress(data) {
    // 这里可以实现真正的压缩算法
    return data
  }

  // 简单的解压方法（示例）
  decompress(data) {
    // 这里可以实现真正的解压算法
    return data
  }

  // 简单的加密方法（示例）
  encrypt(data) {
    // 这里可以实现真正的加密算法
    return data
  }

  // 简单的解密方法（示例）
  decrypt(data) {
    // 这里可以实现真正的解密算法
    return data
  }

  // 设置存储项
  set(key, value) {
    try {
      const fullKey = this.getFullKey(key)
      const serializedValue = this.serialize(value)
      
      wx.setStorageSync(fullKey, serializedValue)
      return true
    } catch (error) {
      console.error('设置存储项失败:', error)
      return false
    }
  }

  // 获取存储项
  get(key, defaultValue) {
    try {
      const fullKey = this.getFullKey(key)
      const serializedValue = wx.getStorageSync(fullKey)
      
      if (!serializedValue) {
        return defaultValue || null
      }
      
      const value = this.deserialize(serializedValue)
      return value
    } catch (error) {
      console.error('获取存储项失败:', error)
      return defaultValue || null
    }
  }

  // 删除存储项
  remove(key) {
    try {
      const fullKey = this.getFullKey(key)
      wx.removeStorageSync(fullKey)
      return true
    } catch (error) {
      console.error('删除存储项失败:', error)
      return false
    }
  }

  // 检查存储项是否存在
  has(key) {
    try {
      const fullKey = this.getFullKey(key)
      const value = wx.getStorageSync(fullKey)
      return value !== '' && value !== null && value !== undefined
    } catch (error) {
      console.error('检查存储项失败:', error)
      return false
    }
  }

  // 清除所有存储项
  clear() {
    try {
      const info = wx.getStorageInfoSync()
      const keys = info.keys.filter(key => key.startsWith(this.prefix))
      
      keys.forEach(key => {
        wx.removeStorageSync(key)
      })
      
      return true
    } catch (error) {
      console.error('清除存储失败:', error)
      return false
    }
  }

  // 获取存储信息
  getInfo() {
    try {
      const info = wx.getStorageInfoSync()
      const filteredKeys = info.keys
        .filter(key => key.startsWith(this.prefix))
        .map(key => key.replace(this.prefix, ''))
      
      return {
        keys: filteredKeys,
        currentSize: info.currentSize,
        limitSize: info.limitSize
      }
    } catch (error) {
      console.error('获取存储信息失败:', error)
      return {
        keys: [],
        currentSize: 0,
        limitSize: 0
      }
    }
  }

  // 设置缓存项（带过期时间）
  setCache(key, data, expireMinutes) {
    try {
        const cacheItem = {
          data,
          timestamp: Date.now(),
          expireTime: expireMinutes ? Date.now() + (expireMinutes * 60 * 1000) : undefined
        }
      
      return this.set(key, cacheItem)
    } catch (error) {
      console.error('设置缓存失败:', error)
      return false
    }
  }

  // 获取缓存项
  getCache(key) {
    try {
        const cacheItem = this.get(key)
      
      if (!cacheItem) {
        return null
      }
      
      // 检查是否过期
      if (cacheItem.expireTime && Date.now() > cacheItem.expireTime) {
        this.remove(key)
        return null
      }
      
      return cacheItem.data
    } catch (error) {
      console.error('获取缓存失败:', error)
      return null
    }
  }

  // 清除过期缓存
  clearExpiredCache() {
    try {
      const info = this.getInfo()
      let clearedCount = 0
      
      info.keys.forEach(key => {
        const cacheItem = this.get(key)
        if (cacheItem && cacheItem.expireTime && Date.now() > cacheItem.expireTime) {
          this.remove(key)
          clearedCount++
        }
      })
      
      return clearedCount
    } catch (error) {
      console.error('清除过期缓存失败:', error)
      return 0
    }
  }

  // 批量设置
  setBatch(items) {
    try {
      Object.entries(items).forEach(([key, value]) => {
        this.set(key, value)
      })
      return true
    } catch (error) {
      console.error('批量设置失败:', error)
      return false
    }
  }

  // 批量获取
  getBatch(keys) {
    const result = {}
    
    keys.forEach(key => {
      result[key] = this.get(key)
    })
    
    return result
  }

  // 批量删除
  removeBatch(keys) {
    try {
      keys.forEach(key => {
        this.remove(key)
      })
      return true
    } catch (error) {
      console.error('批量删除失败:', error)
      return false
    }
  }
}

// 创建存储管理器实例
const storageManager = StorageManager.getInstance()

// 导出基础存储方法
const storage = {
  // 基础方法
  set: (key, value) => storageManager.set(key, value),
  get: (key, defaultValue) => storageManager.get(key, defaultValue),
  remove: (key) => storageManager.remove(key),
  has: (key) => storageManager.has(key),
  clear: () => storageManager.clear(),
  getInfo: () => storageManager.getInfo(),
  
  // 缓存方法
  setCache: (key, data, expireMinutes) => 
    storageManager.setCache(key, data, expireMinutes),
  getCache: (key) => storageManager.getCache(key),
  clearExpiredCache: () => storageManager.clearExpiredCache(),
  
  // 批量方法
  setBatch: (items) => storageManager.setBatch(items),
  getBatch: (keys) => storageManager.getBatch(keys),
  removeBatch: (keys) => storageManager.removeBatch(keys)
}

// 特定业务的存储方法
const userStorage = {
  // 用户信息
  setUserInfo: (userInfo) => storage.set(STORAGE_KEYS.USER_INFO, userInfo),
  getUserInfo: () => storage.get(STORAGE_KEYS.USER_INFO),
  clearUserInfo: () => storage.remove(STORAGE_KEYS.USER_INFO),
  
  // 认证信息
  setToken: (token) => storage.set(STORAGE_KEYS.TOKEN, token),
  getToken: () => storage.get(STORAGE_KEYS.TOKEN),
  setRefreshToken: (token) => storage.set(STORAGE_KEYS.REFRESH_TOKEN, token),
  getRefreshToken: () => storage.get(STORAGE_KEYS.REFRESH_TOKEN),
  setTokenExpiresIn: (expiresIn) => storage.set(STORAGE_KEYS.TOKEN_EXPIRES_IN, expiresIn),
  getTokenExpiresIn: () => storage.get(STORAGE_KEYS.TOKEN_EXPIRES_IN),
  clearAuthData: () => {
    storage.removeBatch([
      STORAGE_KEYS.TOKEN,
      STORAGE_KEYS.REFRESH_TOKEN,
      STORAGE_KEYS.TOKEN_EXPIRES_IN,
      STORAGE_KEYS.USER_INFO
    ])
  },
  
  // 用户设置
  setUserSettings: (settings) => storage.set(STORAGE_KEYS.USER_SETTINGS, settings),
  getUserSettings: () => storage.get(STORAGE_KEYS.USER_SETTINGS, {}),
  updateUserSettings: (updates) => {
    const current = userStorage.getUserSettings()
    const updated = { ...current, ...updates }
    return storage.set(STORAGE_KEYS.USER_SETTINGS, updated)
  }
}

const appStorage = {
  // 应用配置
  setAppConfig: (config) => storage.set(STORAGE_KEYS.APP_CONFIG, config),
  getAppConfig: () => storage.get(STORAGE_KEYS.APP_CONFIG, {}),
  
  // 主题设置
  setTheme: (theme) => storage.set(STORAGE_KEYS.THEME, theme),
  getTheme: () => storage.get(STORAGE_KEYS.THEME, 'light'),
  
  // 语言设置
  setLanguage: (language) => storage.set(STORAGE_KEYS.LANGUAGE, language),
  getLanguage: () => storage.get(STORAGE_KEYS.LANGUAGE, 'zh-CN'),
  
  // 首次启动
  setFirstLaunch: (isFirst) => storage.set(STORAGE_KEYS.FIRST_LAUNCH, isFirst),
  isFirstLaunch: () => storage.get(STORAGE_KEYS.FIRST_LAUNCH, true),
  
  // 版本信息
  setLastVersion: (version) => storage.set(STORAGE_KEYS.LAST_VERSION, version),
  getLastVersion: () => storage.get(STORAGE_KEYS.LAST_VERSION),
  
  // 隐私协议
  setPrivacyAgreed: (agreed) => storage.set(STORAGE_KEYS.PRIVACY_AGREED, agreed),
  isPrivacyAgreed: () => storage.get(STORAGE_KEYS.PRIVACY_AGREED, false)
}

const searchStorage = {
  // 搜索历史
  getSearchHistory: () => storage.get(STORAGE_KEYS.SEARCH_HISTORY, []),
  addSearchHistory: (keyword) => {
    const history = searchStorage.getSearchHistory()
    const filtered = history.filter(item => item !== keyword)
    const updated = [keyword, ...filtered].slice(0, 20) // 最多保存20条
    return storage.set(STORAGE_KEYS.SEARCH_HISTORY, updated)
  },
  clearSearchHistory: () => storage.remove(STORAGE_KEYS.SEARCH_HISTORY),
  
  // 最近访问的胶囊
  getRecentCapsules: () => storage.get(STORAGE_KEYS.RECENT_CAPSULES, []),
  addRecentCapsule: (capsuleId) => {
    const recent = searchStorage.getRecentCapsules()
    const filtered = recent.filter(id => id !== capsuleId)
    const updated = [capsuleId, ...filtered].slice(0, 10) // 最多保存10个
    return storage.set(STORAGE_KEYS.RECENT_CAPSULES, updated)
  },
  clearRecentCapsules: () => storage.remove(STORAGE_KEYS.RECENT_CAPSULES)
}

const cacheStorage = {
  // 胶囊缓存
  setCapsuleCache: (capsuleId, data, expireMinutes = 30) => 
    storage.setCache(`${STORAGE_KEYS.CAPSULE_CACHE}_${capsuleId}`, data, expireMinutes),
  getCapsuleCache: (capsuleId) => 
    storage.getCache(`${STORAGE_KEYS.CAPSULE_CACHE}_${capsuleId}`),
  removeCapsuleCache: (capsuleId) => 
    storage.remove(`${STORAGE_KEYS.CAPSULE_CACHE}_${capsuleId}`),
  
  // 条目缓存
  setEntryCache: (entryId, data, expireMinutes = 30) => 
    storage.setCache(`${STORAGE_KEYS.ENTRY_CACHE}_${entryId}`, data, expireMinutes),
  getEntryCache: (entryId) => 
    storage.getCache(`${STORAGE_KEYS.ENTRY_CACHE}_${entryId}`),
  removeEntryCache: (entryId) => 
    storage.remove(`${STORAGE_KEYS.ENTRY_CACHE}_${entryId}`),
  
  // 模板缓存
  setTemplateCache: (data, expireMinutes = 60) => 
    storage.setCache(STORAGE_KEYS.TEMPLATE_CACHE, data, expireMinutes),
  getTemplateCache: () => 
    storage.getCache(STORAGE_KEYS.TEMPLATE_CACHE),
  
  // 清除所有缓存
  clearAllCache: () => {
    const info = storage.getInfo()
    const cacheKeys = info.keys.filter(key => 
      key.includes('_cache') || key.includes('Cache')
    )
    return storage.removeBatch(cacheKeys)
  }
}

const draftStorage = {
  // 胶囊草稿
  setDraftCapsule: (draft) => storage.set(STORAGE_KEYS.DRAFT_CAPSULE, draft),
  getDraftCapsule: () => storage.get(STORAGE_KEYS.DRAFT_CAPSULE),
  clearDraftCapsule: () => storage.remove(STORAGE_KEYS.DRAFT_CAPSULE),
  
  // 条目草稿
  setDraftEntry: (capsuleId, draft) => 
    storage.set(`${STORAGE_KEYS.DRAFT_ENTRY}_${capsuleId}`, draft),
  getDraftEntry: (capsuleId) => 
    storage.get(`${STORAGE_KEYS.DRAFT_ENTRY}_${capsuleId}`),
  clearDraftEntry: (capsuleId) => 
    storage.remove(`${STORAGE_KEYS.DRAFT_ENTRY}_${capsuleId}`),
  
  // 清除所有草稿
  clearAllDrafts: () => {
    const info = storage.getInfo()
    const draftKeys = info.keys.filter(key => key.includes('draft'))
    return storage.removeBatch(draftKeys)
  }
}

// 导出所有模块
module.exports = {
  storage,
  userStorage,
  appStorage,
  searchStorage,
  cacheStorage,
  draftStorage,
  StorageManager,
  STORAGE_KEYS
}